/**
 * Created by Apple on 2016/7/18.
 */
'use strict';

import DBHelper from './db_helper.js';
//全局缓存
export default new class GlobalCache extends think.controller.base {
    /**
     * some base method in here
     */
    init(http) {
        super.init(http);
        this.userID2AccountMap = {};
        this.gameID2AccountMap = {};
        this.nickname2AccountMap = {};
        this.account2AccountMap = {};       //账号
        this.wxUnionID2AccountMap = {};
        this.wxgzhOpenID2AccountMap = {};

        this.openID2userInfos = {};         //openID2userInfo
        this.unionID2userInfos = {};        //unionID2userInfo

        this.roomID2RoomInfoMap = {};       //房间信息


        this.lastUpdateCacheTime = 0;
        this.updateCacheInterval =3* 60 * 1000;        //默认3分钟


        console.log("new GlobalCache");
        this.autoRefreshCache();
    }

    /**
     * 自动刷新用户信息缓存， 如果距离上次刷新未满5分钟， 则不刷新, 主要缓存 gameID, 跟nickName
     */
    autoRefreshCache() {
        if (Date.now() > this.lastUpdateCacheTime + this.updateCacheInterval) {
            this.lastUpdateCacheTime = Date.now();
            this.refreshAccountCache();
            //this.refreshRoomInfoCache();
        }
    }


    /**
     * 强制刷新房间信息缓存
     */
    refreshRoomInfoCache() {


        DBHelper.getRoomList().then(rows => {
            this.roomID2RoomInfoMap = {};

            for (var i = 0; i < rows[0][0].length; ++i) {
                var roomInfo = rows[0][0][i];
                if (roomInfo) {
                    this.roomID2RoomInfoMap[roomInfo.roomID] = roomInfo;
                }
            }
        })
    }

    /**
     * 强制刷新用户信息缓存
     */
    refreshAccountCache() {


        DBHelper.readAccounts().then(rows => {
			this.userID2AccountMap = {};
            this.gameID2AccountMap = {};
            this.nickname2AccountMap = {};
            this.account2AccountMap = {};       //账号
            this.wxUnionID2AccountMap = {};
            this.wxgzhOpenID2AccountMap = {};
            this.openID2userInfos = {};
            for (var i = 0; i < rows[0][0].length; ++i) {
                var account = rows[0][0][i];
                if (account) {
                    this.userID2AccountMap[account.userID] = account;
                    this.gameID2AccountMap[account.gameID] = account;
                    this.nickname2AccountMap[account.nickname] = account;
                    this.account2AccountMap[account.account] = account;
                    this.wxUnionID2AccountMap[account.wxUnionID] = account;
                    this.wxgzhOpenID2AccountMap[account.wxgzhOpenID] = account;
                    this.openID2userInfos[account.wxgzhOpenID] = account;
                }
            }

        })
    }
}